package org.lightcommons.orm.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.lightcommons.logger.Log;
import org.lightcommons.logger.LogFactory;

/**
 * 
 * @author gl
 * @since Jun 15, 2008
 */
public class ThreadLocalSessionHolder implements SessionHolder{
	private static final Log log = LogFactory
			.getLog(ThreadLocalSessionHolder.class);
	private final ThreadLocal<Session> localSession = new ThreadLocal<Session>();

	private final SessionFactory sessionFactory;

	/**
	 * @param sessionFactory
	 */
	public ThreadLocalSessionHolder(SessionFactory sessionFactory) {
		super();
		this.sessionFactory = sessionFactory;
	}

	public Session getSession() {
		Session s = localSession.get();
		if ((s == null) || !s.isOpen()) {
			s = sessionFactory.openSession();
			localSession.set(s);
		}
		return s;
	}

	public void releaseSession() {
		final Session s = localSession.get();
		localSession.remove();

		if (s != null) {
			if (s.isOpen()) {
				s.close();
				log.debug("closing session");
			}
		}
	}

}
